import login from '@/api/apis/login'
import tool from '@/utils/tool'
import sysRouter from '@/router/systemRouter'
import store from '@/store'
import i18n from '@/locales'
import colorTool from '@/utils/color'
import {RouterView} from 'vue-router'
import {defineStore} from 'pinia'
import useGlobalStore from "@/store/modules/global";

const modules = import.meta.glob('/src/views/**/*.vue')

const useUserStore = defineStore({
	id: 'user',
	state: () => {
		return {
			routers: undefined,
			userInfo: {},
			codes: []
		}
	},
	getters: {},
	actions: {
		SET_ROUTERS(routers) {
			this.routers = routers
		},
		resetState() {
			this.token = ''
			this.userInfo = {}
			this.codes = []
		},
		getUserInfo() {
			const globalStore = useGlobalStore()
			return new Promise((resolve, reject) => {
				login.getInfo().then(response => {
					if (response.data.roles && response.data.routers.length > 0) {
						response.data.routers = filterAsyncRouter(response.data.routers)
						response.data.routers.unshift(sysRouter.dashboard)
						let user = {
							codes: response.data.codes,
							roles: response.data.roles,
							user: response.data.user
						}
						this.userInfo = user.user
						this.codes = user.codes
						if (user.user && user.user.backend_setting) {
							let backend_setting = user.user.backend_setting
							// let backend_setting = JSON.parse(user.user.backend_setting)
							tool.data.set('LAYOUT_TAGS', backend_setting.layoutTags)
							tool.data.set('APP_LAYOUT', backend_setting.layout)
							tool.data.set('APP_LANG', backend_setting.lang)
							tool.data.set('APP_THEME', backend_setting.theme)
							tool.data.set('APP_COLOR', backend_setting.colorPrimary)
							// 设置tag
							if (globalStore.layoutTags !== backend_setting.layoutTags) {
								//commit('TOGGLE_layoutTags')
								globalStore.TOGGLE_layoutTags()
							}
							// 设置语言
							i18n.locale = backend_setting.lang
							// 设置布局
							globalStore.SET_layout(backend_setting.layout)
							//commit("SET_layout", backend_setting.layout)
							// 是否黑夜模式
							backend_setting.theme === 'dark' ? document.documentElement.classList.add("dark") : document.documentElement.classList.remove("dark")
							// 设置主题颜色
							colorTool.setPrimaryColor(backend_setting.colorPrimary, backend_setting.theme)
						}
						// commit('TOGGLE_layoutTags')
						this.routers = response.data.routers
						tool.data.set('user', user)
						resolve(response.data)
					}
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
})

//转换
const filterAsyncRouter = (routerMap) => {
	const accessedRouters = []
	routerMap.forEach(item => {
		if (item.meta.type == 'B') {
			return
		}
		item.meta = item.meta ? item.meta : {};
		//处理外部链接特殊路由
		if (item.meta.type == 'I') {
			item.meta.url = item.path
			item.path = `/i/${item.name}`
		}
		//MAP转路由对象
		const route = {
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterAsyncRouter(item.children) : null,
			component: loadRouteView(item.component)
		}
		accessedRouters.push(route)
	})
	return accessedRouters
}

// function loadComponent(component) {
//   if (component) {
//     return () => import( `../../views/${component}`)
//   } else {
//     return () => import(`../../layout/other/empty`)
//   }
// }

// 动态加载组件
const loadRouteView = (component) => {
	try {
		const key = Object.keys(modules).find((key) => {
			return key.includes(`${component}.vue`)
		})
		if (key) {
			return modules[key]
		}
		throw Error(`找不到组件${component}，请确保组件路径正确`)
	} catch (error) {
		console.error(error)
		//return () => import(`/scr/layout/other/empty`)
		return RouterView
	}
}

export default useUserStore
